package com.siwei.mes.common.mybatis.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author chenmaolin
 * @date: 2021/12/6 16:15
 */
@MappedTypes(value = {JSONObject.class})  // 此转换器可以自动转换为的java对象
@MappedJdbcTypes(value = {JdbcType.VARCHAR}) // 注解中设置的是对应的jdbctype，mysql的json对象对应的jdbctype为VARCHAR。
public class JsonTypeHandler<T extends Object> extends BaseTypeHandler<T> {

    private Class<T> clazz;

    public JsonTypeHandler() {
    }

    public JsonTypeHandler(Class<T> clazz) {
        this.clazz = clazz;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, JSON.toJSONString(parameter));
    }

    @Override
    public T getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String data = resultSet.getString(columnName);
        return StringUtils.isBlank(data) ? null : JSON.parseObject(data, clazz);
    }

    @Override
    public T getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException {
        String data = resultSet.getString(columnIndex);
        return StringUtils.isBlank(data) ? null : JSON.parseObject(data, clazz);
    }

    @Override
    public T getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException {
        String data = callableStatement.getString(columnIndex);
        return StringUtils.isBlank(data) ? null : JSON.parseObject(data, clazz);
    }
}